package com.edol.painting.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import java.util.List;

/**
 * Created by guanrui on 15-1-17.
 */
public class ChangeBgAnim {
    private ChangeBgAnimSet mChangeBgAnimSet;
    private List<Bitmap> mFrames;
    private float mCenterOffset;
    private Paint mPaint;
    private RectF mCanvasRectF;
    private int mAlpha = 0;

    public ChangeBgAnim(Resources res) {
        init(res);
    }

    private void init(Resources res) {
        mChangeBgAnimSet = new ChangeBgAnimSet(res);
    }

    public void prepare(Paint paint, float center) {
        mPaint = paint;

        mChangeBgAnimSet.initFrames();
        mFrames = mChangeBgAnimSet.getFrames();
        float width = mFrames.get(0).getWidth();
        float height = mFrames.get(0).getHeight();

        float scale = Constant.PAINTING_HEIGHT / height;
        float maxExpand = (width * scale - Constant.PAINTING_WIDTH) / 2;

        float offset = Constant.PAINTING_WIDTH / 2 - center;
        mCenterOffset = offset / (Constant.PAINTING_EDIT_CHANGE_BACKGROUND_FRAME - 1);
        mCanvasRectF = new RectF(-maxExpand, 0, Constant.PAINTING_WIDTH + maxExpand, Constant.PAINTING_HEIGHT);
        mCanvasRectF.offset(-offset, 0);
    }

    public void start(int i, Canvas canvas) {
        changeRect(i);
        canvas.saveLayerAlpha(mCanvasRectF, mAlpha, Canvas.ALL_SAVE_FLAG);
        canvas.drawBitmap(mFrames.get(i), null, mCanvasRectF, null);
        canvas.drawRect(mCanvasRectF, mPaint);
        canvas.restore();
        if (i == (Constant.PAINTING_EDIT_CHANGE_BACKGROUND_FRAME - 1)) {
            mCanvasRectF.setEmpty();
        }
    }

    private void changeRect(int i) {
        if (i != 0) {
            mCanvasRectF.offset(mCenterOffset, 0);
            mAlpha = mAlpha < 255 ? mAlpha + 32 : 255;
        }
    }

    public void clear() {
        mChangeBgAnimSet.clear();
    }

}
